/*
  学习目标：评论列表-组件改造



*/

import React from 'react';
import './index.css';
export default class App extends React.Component {
  state = {
    username: '',
    content: '',
    list: [
      {
        id: 1,
        username: '思聪',
        content: '想你的夜',
      },
      {
        id: 2,
        username: '思聪2',
        content: '想你的夜2',
      },
      {
        id: 3,
        username: '思聪3',
        content: '想你的夜3',
      },
    ],
  };

  handleChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleSubmit = (e) => {
    e.preventDefault();

    if (!this.state.username.trim() || !this.state.content.trim()) return alert('别乱写');

    this.setState({
      list: [
        {
          id: Date.now(),
          username: this.state.username,
          content: this.state.content,
        },
        ...this.state.list,
      ],

      username: '',
      content: '',
    });
  };

  handleDel = (id) => {
    this.setState({ list: this.state.list.filter((item) => item.id !== id) });
  };

  handleClear = () => {
    this.setState({ list: [] });
  };

  render() {
    const { username, content } = this.state;
    return (
      <div className="app">
        {/* 表单提交的时候，运行发布评论的函数 */}
        {/*  2.1 表单元素改成受控组件 - 为了能够收集用户输入的数据 */}
        <form onSubmit={this.handleSubmit}>
          <input
            className="user"
            type="text"
            placeholder="请输入评论人"
            value={username}
            name="username"
            onChange={this.handleChange}
          />
          <br />
          <textarea
            className="content"
            cols="30"
            rows="10"
            placeholder="请输入评论内容"
            value={content}
            name="content"
            onChange={this.handleChange}
          />
          <br />
          <button>发表评论</button>

          <button type="button" onClick={this.handleClear}>
            清空评论
          </button>
        </form>
        {/*   1. 将列表ul拆为单独的组件 */}
        {!this.state.list.length ? (
          <div>暂无数据</div>
        ) : (
          // 2. 父传子技术传list过去
          <CommentList list={this.state.list} handleDel={this.handleDel}></CommentList>
        )}
      </div>
    );
  }
}

function CommentList({ list, handleDel }) {
  return (
    <ul>
      {list.map((item) => {
        return (
          <li key={item.id}>
            <h3>评论人: {item.username}</h3>
            <p>评论内容：{item.content}</p>
            {/* 3. 子传父技术，调用父组件的删除方法  */}
            <button onClick={() => handleDel(item.id)}>删除</button>
          </li>
        );
      })}
    </ul>
  );
}
